import { Request, Response, NextFunction } from 'express';
import { ApiResponse } from '../types';

// 请求验证中间件
export const validateRequest = (requiredFields: string[]) => {
  return (req: Request, res: Response, next: NextFunction) => {
    const missingFields = requiredFields.filter(field => !req.body[field]);
    
    if (missingFields.length > 0) {
      const response: ApiResponse = {
        success: false,
        error: `缺少必填字段: ${missingFields.join(', ')}`,
      };
      res.status(400).json(response);
      return;
    }
    
    next();
  };
};

// 设备ID验证中间件
export const validateDeviceId = (req: Request, res: Response, next: NextFunction) => {
  const { deviceId } = req.params;
  
  if (!deviceId || deviceId.trim() === '') {
    const response: ApiResponse = {
      success: false,
      error: '设备ID不能为空',
    };
    res.status(400).json(response);
    return;
  }
  
  // 这里可以添加更多的设备ID格式验证
  if (!/^[a-zA-Z0-9_-]+$/.test(deviceId)) {
    const response: ApiResponse = {
      success: false,
      error: '设备ID格式不正确',
    };
    res.status(400).json(response);
    return;
  }
  
  next();
};

// 请求限流中间件（简单实现）
const requestCounts = new Map<string, { count: number; resetTime: number }>();

export const rateLimiter = (maxRequests: number = 100, windowMs: number = 60000) => {
  return (req: Request, res: Response, next: NextFunction) => {
    const clientId = req.ip || 'unknown';
    const now = Date.now();
    
    const clientData = requestCounts.get(clientId);
    
    if (!clientData || now > clientData.resetTime) {
      // 重置计数器
      requestCounts.set(clientId, {
        count: 1,
        resetTime: now + windowMs,
      });
      next();
      return;
    }
    
    if (clientData.count >= maxRequests) {
      const response: ApiResponse = {
        success: false,
        error: '请求频率过高，请稍后再试',
      };
      res.status(429).json(response);
      return;
    }
    
    clientData.count++;
    next();
  };
};